package com.se.nju.rtvps.network;

import com.se.nju.rtvps.main.ServiceConstants;
import com.se.nju.rtvps.main.StartUp;
import com.se.nju.rtvps.service.ControlService;

import net.jxta.discovery.DiscoveryService;
import net.jxta.document.AdvertisementFactory;
import net.jxta.id.IDFactory;
import net.jxta.pipe.PipeID;
import net.jxta.platform.ModuleClassID;
import net.jxta.protocol.ModuleClassAdvertisement;
import net.jxta.protocol.ModuleSpecAdvertisement;
import net.jxta.protocol.PipeAdvertisement;

public class ServerSidePipeAdvServiceImpl implements PipeAdvService{

	public PipeAdvertisement getControlServicePipeAdv() throws Exception{
		PipeAdvertisement controlService_pipeAdv = publishPipeServiceAdv(
				ServiceConstants.SERVERSIDE_CONTROL_SERVICE_MODNAME,
				ServiceConstants.SERVERSIDE_CONTROL_SERVICE_SPECNAME);
		return controlService_pipeAdv;
	}
	
	public PipeAdvertisement publishPipeServiceAdv(String modname, String specname)throws Exception{
		DiscoveryService discovery = StartUp.getRTVPSPeerGroup().getDiscoveryService();
		ModuleClassAdvertisement mcadv = (ModuleClassAdvertisement)AdvertisementFactory.newAdvertisement(ModuleClassAdvertisement.getAdvertisementType());
		mcadv.setName(modname);
		ModuleClassID mcID = IDFactory.newModuleClassID();
		mcadv.setModuleClassID(mcID);
		discovery.publish(mcadv);
		discovery.remotePublish(mcadv);
		
		ModuleSpecAdvertisement mdadv = (ModuleSpecAdvertisement)AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType());

		mdadv.setName(specname);
		mdadv.setCreator("se.nju.com");
		mdadv.setModuleSpecID(IDFactory.newModuleSpecID(mcID));
		//mdadv.setSpecURI("http://www.jxta.org/Ex1");
		PipeAdvertisement pipeAdv = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());
		PipeID pipeId= IDFactory.newPipeID(RTVPSPeerGroup.CUSTOM_PEERGROUP_ID);
		pipeAdv.setPipeID(pipeId);
		mdadv.setPipeAdvertisement(pipeAdv);
		discovery.publish(mdadv);
		discovery.remotePublish(mdadv);
		return pipeAdv;
	}
}
